/**
 * 单位页面
 */

import { useRecoilState } from "recoil";
import { BaseContiner, FlexContainer, LeftContainer, RightContainer, TableContainer, TableHeader } from "../../../csscomponents/base";
import { useCallback, useRef, useState } from "react";
import { IFormRef, IRoleRestFillRefHandler } from "../../../types";
import { Button, Col, Flex, Form, Input, Modal, Row, Space, Table } from "antd";
import { ErrorBox } from "../../../components/error-box";
import {
    PlusOutlined,
    SearchOutlined
} from '@ant-design/icons';
import { userState } from "../../../stores/user";
import { QueryUnitListParams, SysUnit, useDeleteUnitTree, useGetUnitType, useUnitList } from "../../../service/unit-service";
import UnitTree from "../../../components/unit-tree";
import UnitFrom from "./unit-form";
import { useForm } from "antd/es/form/Form";
import SqForm from "./sequ-form";

const UnitPage = () => {
    const [sys] = useRecoilState(userState);
    const [openDraw, setOpenDraw] = useState<boolean>(false);
    const [updateUnit, setUpdateUnit] = useState<SysUnit>();
    const unitFormRef = useRef<IFormRef>();
    const [queryForm] = useForm();
    const unitTreeRef = useRef<IRoleRestFillRefHandler>();

    const [modal, setModal] = useState<boolean>(false);

    const [queryParams, setQueryParams] = useState<QueryUnitListParams>({
        page: 1,
        limit: 10,
        unitId: sys.userInfo.unitId || '',
        unitName: '',
    });
    /**
        * !获取单位类型HOOK
        */
    const { data: unitTypeDataSource } = useGetUnitType();
    /**
     * !删除单位HOOK
     */
    const { mutateAsync: deleteUnitMutation, isLoading: DIsLoading } = useDeleteUnitTree();
    /**
     * !获取管理员HOOK
     */
    const { isLoading, isError, data: dataSource, error, refetch } = useUnitList(queryParams);

    /**单位选中回调 */
    const getCheckUnit = (unitId: string, unitName: string) => {
        if (unitId && unitId !== queryParams.unitId) {
            setQueryParams({ ...queryParams, unitId: unitId, unitName: queryForm.getFieldValue("unitName") });
        }
    };
    const openModal = useCallback((open: boolean) => {
        setModal(open)
    }, [])

    /**搜索单位 */
    const searchData = (value: { unitName: string }) => {
        setQueryParams({
            ...queryParams,
            unitName: value.unitName,
            page: 1,
            limit: 10
        });
    };
    /**
     * 重置搜索
     */
    const resetQueryParams = () => {
        setQueryParams({
            page: 1,
            limit: 10,
            unitId: sys.userInfo.unitId || '',
            unitName: '',
        })
        unitTreeRef.current?.rest()
        queryForm.resetFields();
    }
    /**删除单位 */
    const removeUnitHandler = (unitId: string) => {
        Modal.confirm({
            title: '⚠️警告',
            content: '你确认执行改操作吗?',
            okText: '确认',
            cancelText: '取消',
            onOk: async () => {
                await deleteUnitMutation({ unitId });
                unitTreeRef.current?.rest();
                refetch();
            },
        });
    };
    /**
     * 更新单位信息
     */
    const updateUnitHandler = (unit: SysUnit) => {
        setUpdateUnit(unit);
        setOpenDraw(true);
        unitTreeRef.current?.rest();
    };

    const [sqFormUnit, setSqFormUnitId] = useState<string>();
    const openUnitModal = (unitId: string) => {
        setSqFormUnitId(unitId);
        setModal(true)
    }

    const columns = [
        {
            title: '单位名称',
            dataIndex: 'unitName',
        },
        {
            title: '单位编码',
            dataIndex: 'unitCode',
        },
        {
            title: '单位类别',
            dataIndex: 'unitType',
            render(item: number) {
                const arr = unitTypeDataSource?.filter(type => type.unitTypeId === item);
                if (arr && arr.length > 0) {
                    return arr[0].unitTypeName
                }
            }
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
        },
        {
            title: '排序',
            dataIndex: 'orderId',
        },
        {
            title: '更多操作',
            render(project: SysUnit) {
                return (
                    <div>
                        <Button style={{ marginRight: '1.2rem' }} danger onClick={() => openUnitModal(project.unitId)}>
                            查看社区
                        </Button>
                        <Button style={{ marginRight: '1.2rem' }} onClick={() => updateUnitHandler(project)}>
                            修改
                        </Button>
                        <Button loading={DIsLoading} danger onClick={() => removeUnitHandler(project.unitId)}>
                            删除
                        </Button>
                    </div>
                );
            },
        },
    ];
    /**
    * 分页配置
    */
    const paginationProps = {
        total: dataSource?.count,
        pageSize: queryParams.limit,
        current: queryParams.page,
        showTotal: (count: number) => {
            return `共 ${count} 条`;
        },
        onChange: (pageNum: number) => {
            setQueryParams({ ...queryParams, page: pageNum });
        },
    };
    return (
        <FlexContainer>
            <LeftContainer>
                <UnitTree getCheckUnit={getCheckUnit} onRef={unitTreeRef} />
            </LeftContainer>
            <RightContainer>
                <BaseContiner>
                    <TableHeader>
                        <Form onFinish={searchData} name="unit_search_form" style={{ width: '100%' }} form={queryForm}>
                            <Row gutter={16}>
                                <Col span={10}>
                                    <Form.Item label="单位名称" name={'unitName'}>
                                        <Input />
                                    </Form.Item>
                                </Col>
                                <Col span={10}>
                                    <Form.Item>
                                        <Space>
                                            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                                搜索
                                            </Button>
                                            <Button type="primary" onClick={() => resetQueryParams()}>
                                                重置
                                            </Button>
                                        </Space>
                                    </Form.Item>
                                </Col>
                                <Col span={4}>
                                    <Flex gap="small" justify="flex-end">
                                        <Form.Item>
                                            <Button type={'primary'} icon={<PlusOutlined />} onClick={() => { setOpenDraw(true) }} >
                                                添加
                                            </Button>
                                        </Form.Item>
                                    </Flex>
                                </Col>
                            </Row>
                        </Form>
                    </TableHeader>
                    <TableContainer>
                        {isError ? (
                            <ErrorBox error={error as { message: string }} />
                        ) : (
                            <Table rowSelection={{ type: 'checkbox' }} dataSource={dataSource?.list} columns={columns} loading={isLoading} pagination={paginationProps} rowKey={(row) => row?.unitId} />
                        )
                        }
                    </TableContainer>
                </BaseContiner>
            </RightContainer>
            <UnitFrom
                onRef={unitFormRef}
                open={openDraw}
                onClose={() => { setOpenDraw(false); setUpdateUnit(undefined) }}
                refetch={refetch}
                openFn={setOpenDraw}
                parentId={queryParams.unitId}
                parentName={unitTreeRef.current?.getData?.().name}
                updateUnit={updateUnit}
                footer={
                    <>
                        {updateUnit ? (
                            <Button
                                onClick={() => {
                                    unitFormRef.current?.update();
                                    unitTreeRef.current?.rest();
                                }}
                            >
                                修改
                            </Button>
                        ) : (
                            <Button
                                onClick={() => {
                                    unitFormRef.current?.save();
                                    unitTreeRef.current?.rest();
                                }}
                            >
                                保存
                            </Button>
                        )}
                    </>
                }
            />
            <SqForm open={modal} setOpen={openModal} unitId={sqFormUnit} />
        </FlexContainer>
    );
};

export default UnitPage;







